package com.hmall.gateway.filters;
/*
  Date: 2023/12/02
  Author: Luochao
  Description:
*/

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * 登录校验
 */
@Component
@RequiredArgsConstructor
public class AuthCheckFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();

        // 2.判断是否需要拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);          //如果排除，不用校验
        }

        // 3.获取Token
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
        if (authorization != null && !authorization.isEmpty()) {
            token = authorization.get(0);
        }

        // 4.校验token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //拦截,响应401
            ServerHttpResponse response = exchange.getResponse();

            response.setStatusCode(HttpStatus.UNAUTHORIZED);    //401
            return response.setComplete();      //拦截
        }

        // 5.传递用户信息
        System.out.println("请求用户Id:"+userId);

        String finalUserId = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(builder -> {
                    builder.header("user-info", finalUserId);
                }).build();

        // 6.放行
        return chain.filter(serverWebExchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath, path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;      //值越小，优先级越大
    }
}
